/**
 * 设置一个cookie
 * @param {string} key cookie的key
 * @param {string} value cookie的值
 * @param {number} maxAge cookie的有效时长（毫秒） 3600000
 * @param {string}  path cookie的有效路径
 */
function setCookie(key, value, maxAge, path = "/") {
  document.cookie =
    `${key}=${value};path=${path};` +
    (maxAge
      ? `expires=${new Date(Date.now() - 8 * 3600 * 1000 + maxAge).toString()}`
      : "");
}

function deleteCookie(key, path = "/") {
  document.cookie = `${key}=我不入地狱谁爱入谁入;path=${path};expires=${new Date(
    1970,
    0,
    1
  )}`;
}

/**
 * 获取所有cookie
 * @returns 所有cookie形成的对象
 */
function getAllCookie() {
  //'a=123; b=456; ts_uid=8310895583'
  const obj = {};
  const str = document.cookie;
  const arr = str.split("; "); //[a=123,b=456]
  arr.forEach((s) => {
    let [key, value] = s.split("="); //[a,123]
    obj[key] = value; //{a:123}
  });
  return obj;
}

/**
 * 获取指定key的cookie值
 * @param {string} key cookie的key
 * @returns 要查询的cookie值
 */
function getCookie(key) {
  return getAllCookie()[key];
}
